﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.DomainObject.Tray;
using WMS.FC.Domain.PersistenceObject.Business;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.Location.Interface;
using WMS.FC.Domain.Service.System;

namespace WMS.FC.Domain.Service.Location
{
    public class GetInboundLocationService : ServiceBase, IGetInboundLocationService
    {
        protected readonly ILocationRepository locationRepository;

        public GetInboundLocationService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            ILocationRepository locationRepository)
            : base(logger, options, mapper)
        {
            this.locationRepository = locationRepository;
        }

        public async Task<ActionResult<LocationPO>> GetInboundLocation(string zoneCode, string lineCode, List<string> equipmentCodeList, TrayDO tray, UserInfo userInfo)
        {
            var result = new ActionResult<LocationPO>("入库货位分配");
            try
            {
                var locationStateList = new List<string>()
                {
                    "LocationState_Empty"
                };

                var locationUseStateList = new List<string>()
                {
                    "LocationUseState_Enabled",
                    "LocationUseState_OnlyInbound"
                };

                var locationPOList = await locationRepository.FindByCondition<LocationPO>(entity => entity.ZoneCode == zoneCode && entity.LineCode == lineCode && equipmentCodeList.Contains(entity.EquipmentCode) && locationStateList.Contains(entity.StateCode) && locationUseStateList.Contains(entity.UseStateCode));

                if (locationPOList.Count == 0)
                    return result.BusinessError($"区域:({zoneCode}),产线:({lineCode}),堆垛机:({string.Join(",", equipmentCodeList)}),当前没有可用货位");

                var line = locationPOList.GroupBy(entity => entity.Line).OrderBy(group => group.Count()).First().Key;
                var locationPO = locationPOList.Where(entity => entity.Line == line).OrderBy(entity => entity.Column).OrderBy(entity => entity.Layer).First();

                locationPO.StateCode = "LocationState_In";
                locationPO.Message = "入库货位分配";

                var count = await locationRepository.Update(locationPO, userInfo);
                if (count == 0)
                    return result.DbError($"货位:{locationPO.Code},更新货位状态异常");

                result.Data = locationPO;
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
